<?php

namespace App\Http\Controllers\Goods;

use App\Http\Requests\GoodsRequest;
use App\Models\Attribute;
use App\Models\AttributeClassify;
use App\Models\AttributeGoods;
use App\Models\Classify;
use App\Models\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    public function index()
    {
        
        $goods=Goods::paginate(10);
      
      return view('goods.goods.index',compact('goods'));
    }
    
    public function create()
    {
        $classify=Classify::where('pid',0)->get();
      return view('goods.goods.create',compact('classify'));
    }
    public function store(GoodsRequest $request)
    {
        $goods=Goods::create($request->all());
        foreach ($request->attribute as $item){
            AttributeGoods::create([
                'attribute_id'=>$item,
                'goods_id'=>$goods->id,
            ]);
        }
        return back();
//        return redirect()->route('goods.goods.index')->with('success','添加商品成功');
    }
    public function show(Goods $good)
    {
    }
    public function edit(Goods $good)
    {
     $clssifyIds=$good->classify_id;
        $classifyfirst=Classify::where('pid',0)->get();//3
        $classifysecond=Classify::where('pid',$clssifyIds[0])->get();
        $classifythird=Classify::where('pid',$clssifyIds[1])->get();
        //此商品对应的属性id
        
        $attrId=AttributeGoods::where('goods_id',$good->id)->pluck('attribute_id')->toArray();
//        dump($attrId);
        //获取所有的顶级属性
        $attrIds=Attribute::where('pid',0)->get()->toArray();
//        dump($attrIds);
       
//   dd(11);
       return view('goods.goods.edit',compact('classifyfirst','classifysecond','classifythird','attrId','attrIds','good','clssifyIds'));
    }
    public function update(GoodsRequest $request, Goods $good)
    {
//        dd($request->toArray());
        $good->update($request->all());
        $attribute=$request->attribute;
//        dd($attribute);
      $attr= AttributeGoods::where('goods_id',$good->id)->get();
      foreach ($attr as $v){
          $v->delete();
      }
      foreach ($attribute as $value){
          AttributeGoods::create([
              'goods_id'=>$good->id,
              'attribute_id'=>$value
          ]);
      }
        return redirect()->route('goods.goods.index')->with('success','商品编辑成功');
    }
    public function destroy(Goods $good)
    {
        $attr= AttributeGoods::where('goods_id',$good->id)->get();
        foreach ($attr as $v){
            $v->delete();
        }
        $good->delete();
        return back()->with('success','商品删除成功');
    }
}
